package com.sparrow.common.util;

import com.thoughtworks.qdox.JavaProjectBuilder;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaField;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * java源码辅助类
 */
public class JavaSourceHelper {

    public static void main(String[] args) {
        Map<String, Map<String, String>> comments = getFieldsComments("C:\\Users\\liushengbao\\IdeaProjects\\sparrow\\common\\src\\test\\java\\com\\sparrow\\common\\TestBean.java");
        String str = JsonUtil.formatJSON(JsonUtil.toJSON(comments));
        System.out.println(str);
    }


    /**
     * 获取字段的注释
     * @param path
     * @return
     */
    public static Map<String, Map<String, String>> getFieldsComments(String path) {
        try {
            JavaProjectBuilder builder = new JavaProjectBuilder();
            builder.addSource(new File(path));
            Map<String, Map<String, String>> map = new HashMap<>();
            for (JavaClass cls : builder.getClasses()) {
                List<JavaField> fields = cls.getFields();
                Map<String, String> comments = new HashMap<>();
                for (JavaField e : fields) {
                    String comment = e.getComment();
                    comments.put(e.getName(), comment);
                }
                map.put(cls.getName(), comments);
            }
            return map;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
